<!-- For Changes See Changes log at http://code.google.com/p/io-meta/source/list -->

<style type="text/css">
	body {font-family:"Helvetica Neue", Arial, sans-serif;font-size:.9em;}
</style><?php
$xmlFile = $_GET['xmlFile'];
if (!$xmlFile) {
	$xmlFile = "specs.xml";
}


parseXML();
dataToStrings();
createGlobalData();
echo "<pre>".print_r($xml_data, TRUE)."</pre>";
//print_r($xml_data);

$xml_data = array();
$displayNameArray = array();
$tableArray = array();

global $db_host;
global $db_username;
global $db_password;
global $db_name;
global $images_path,$movies_path,$audio_path;
global $siteName,$tableArray,$inputElementsString, $fieldVarsString, $postDataVarsString, $fieldsForDeletionString;
global $backListElements, $frontListElements, $frontListSQL, $backListSQL, $listPageNav;

// parseXML() reads from $_GET['xmlFile'] file 
function parseXML() {
	global $xmlFile;
	global $optionCounter;
	$optionCounter = 0;
	if (! ($xmlparser = xml_parser_create()) )
	{ 
		die ("Cannot create parser");
	} //instantiate the xml parser

	function start_tag($parser, $name, $attribs) { //function that processes start tags
		global $current;
		global $currentGrandparent;
		global $currentParent;
		global $siteName;
		global $xml_data;
		global $optionCounter, $listPageNav, $tableArray,$displayNameArray;
		global $site_name;
		
		 //global array for containing sql data

		$current = $name;
		switch ($name) {
		case "SITE":
			echo "<h1>Site Name: ".$attribs["NAME"]."</h1>";
			$site_name = $siteName = $attribs["NAME"];			 
			break;
		case "TABLE":
			$xml_data[$attribs["NAME"]];
			$currentGrandparent = $attribs["NAME"];
			$tableArray[] = $currentGrandparent;
			$xml_data[$attribs["NAME"]]["DISPLAYNAME"];
			$xml_data[$attribs["NAME"]]["DISPLAYNAME"] = $attribs["DISPLAYNAME"];
			if ($attribs["SORTABLE"]) {
				$xml_data[$attribs["NAME"]]["SORTABLE"];
				$xml_data[$attribs["NAME"]]["SORTABLE"] = $attribs["SORTABLE"];
				$xml_data[$attribs["NAME"]]["sort_order"];
				$xml_data[$attribs["NAME"]]["sort_order"]["DISPLAYNAME"];
				$xml_data[$attribs["NAME"]]["sort_order"]["DISPLAYNAME"] = "Sort Order";				
				$xml_data[$attribs["NAME"]]["sort_order"]["SQLDATATYPE"] = "INT";
				$xml_data[$attribs["NAME"]]["sort_order"]["ENTRYMETHOD"] = "hidden";
				$xml_data[$attribs["NAME"]]["sort_order"]["FRONTLIST"] = "none";
				$xml_data[$attribs["NAME"]]["sort_order"]["BACKLIST"] = "none";
			}
			if ($attribs["STATIC"]) {
				$xml_data[$attribs["NAME"]]["STATIC"] = 1;
/* 				$xml_data[$attribs["NAME"]]["SORTABLE"] = $attribs["SORTABLE"]; */
			}			
			if ($attribs["HAS_TITLE"]) {
				$xml_data[$attribs["NAME"]]["HAS_TITLE"] = 1;
			}			
			$displayNameArray[$currentGrandparent] = $attribs["DISPLAYNAME"];
			$listPageNav .= "<div id='" . $attribs["NAME"] . "' class='pageNav'><a href='" . $attribs["NAME"] . "_list.php'>" . $attribs["NAME"] . "</a></div>";
			//echo "<h2>Tablename: ";
			break;
		case "FIELD":
			$optionCounter = 0; //when you reach a new field, reset the option counters so the indexes are consistent
			$xml_data[$currentGrandparent][$attribs["NAME"]];
			$currentParent = $attribs["NAME"];
			$xml_data[$currentGrandparent][$attribs["NAME"]]["DISPLAYNAME"];
			$xml_data[$currentGrandparent][$attribs["NAME"]]["DISPLAYNAME"] = $attribs["DISPLAYNAME"];
			if (strtoupper($attribs["DISPLAYNAME"]) == "TITLE") {
				$xml_data[$currentGrandparent]["HAS_TITLE"] = true;
			}
			//echo "<div style='border:1px solid #000;'>";
			break;
		case "LINKED_TABLES":
			$xml_data[$name];
			$currentGrandparent = $name;
			break;
		case "RELATIONSHIP":
			$xml_data[$currentGrandparent];
			$currentParent = $attribs["LINK"];
			//echo "in RELATIONSHIP currentGP = $currentGrandparent currentParent : $currentParent <br>\n";
			break;
		case "BROTHER":
		case "SISTER":
			$xml_data[$currentGrandparent][$currentParent][$name];
			break;
		case "SQLDATATYPE":		//##################################################
		case "ENTRYMETHOD":		//for the info contained within each "FIELD" element
		case "FRONTLIST":			//##################################################
		case "BACKLIST":			//##################################################
			$xml_data[$currentGrandparent][$currentParent][$name];
			if ($attribs["CHILD_TABLENAME"]) {
				$xml_data[$currentGrandparent][$currentParent]["CHILD_TABLENAME"];
				$xml_data[$currentGrandparent][$currentParent]["CHILD_TABLENAME"] = $attribs["CHILD_TABLENAME"];
				$xml_data[$currentGrandparent][$currentParent]["CHILD_FIELDNAME"];
				$xml_data[$currentGrandparent][$currentParent]["CHILD_FIELDNAME"] = $attribs["CHILD_FIELDNAME"];
			}
			if ($attribs["LINK_TABLENAME"]) {
				$xml_data[$currentGrandparent][$currentParent]["LINK_TABLENAME"];
				$xml_data[$currentGrandparent][$currentParent]["LINK_TABLENAME"] = $attribs["LINK_TABLENAME"];			
				$xml_data[$currentGrandparent]["NUM_LINKTABLEFIELDS"] = $xml_data[$currentGrandparent]["NUM_LINKTABLEFIELDS"]+1;	
			}
			if ($attribs["WIDTH"]) {
				$xml_data[$currentGrandparent][$currentParent]["WIDTH"];
				$xml_data[$currentGrandparent][$currentParent]["WIDTH"] = $attribs["WIDTH"];
				$xml_data[$currentGrandparent][$currentParent]["HEIGHT"];
				$xml_data[$currentGrandparent][$currentParent]["HEIGHT"] = $attribs["HEIGHT"];
			}
			if ($attribs["SORTABLE"]) {
				$xml_data[$currentGrandparent][$currentParent]["SORTABLE"];
				$xml_data[$currentGrandparent][$currentParent]["SORTABLE"] = $attribs["SORTABLE"];
			}
			break;
		case "OPTION":
			//echo "in OPTION currentGP = $currentGrandparent currentParent : $currentParent <br>\n";
			$optionCounter++;
			break;
		case "GLOBALS":
			$xml_data[$name];
			$currentGrandparent = $name;
			break;
		case "AUDIO_PATH":		//###################################################
		case "IMAGES_PATH":		//###################################################
		case "THUMBS_PATH":		//
		case "MOVIES_PATH":		//
		case "USERNAME":			//for the info contained within each "GLOBAL" element
		case "PASSWORD":			//
		case "DATABASE":			//###################################################
		case "HOST":					//###################################################
		case "HTTP_ROOT":			//###################################################
		case "SERVER_ROOT":		//###################################################
			//echo "IN GLOBALS // currentGP : $currentGrandparent currentParent : $currentParent <br>\n";
			$xml_data[$currentGrandparent][$current];
			break;
		default:
			echo "<b>ERROR: incorrect XML structure // $value / $name</b><br/>";
		}
/*
		echo "currentGP : $currentGrandparent currentParent : $currentParent <br>\n";
		echo "currentEntry : " . print_r($xml_data);
		echo "\n<br><br>";

	  	echo "Current tag : ".$name."<br />";
	  	if (is_array($attribs)) {
	      echo "Attributes : <br />";
	      while(list($key,$val) = each($attribs)) {
	         echo "Attribute ".$key." has value ".$val."<br />";
	       }
	    }
*/    
	} //end parseXML()
	
	function end_tag($parser, $name) { //function that processes end tags
//	   echo "Reached ending tag ".$name."<br /><br />";
		switch ($name) {
			case "SITENAME":
				break;
			case "TABLENAME":
				break;
			case "FIELD":
				break;
			case "NAME":
				break;
		}
	}
	xml_set_element_handler($xmlparser, "start_tag", "end_tag"); //calls the xml parser, sets the start/end tag functions
	
	function tag_contents($parser, $data) { //function that reads data within tags
		global $xml_data;
		global $current;
		global $currentParent;
		global $currentGrandparent;
		global $optionCounter;
		
		//echo "INSIDE TAG CONTENTS // currentGP : $currentGrandparent currentParent : $currentParent current : $current data : $data <br>\n";
		if ($currentGrandparent == "LINKED_TABLES") {
			$xml_data[$currentGrandparent][$currentParent][$current] = $data."_id";
			}
		else if ($currentGrandparent == "GLOBALS") {
			$xml_data[$currentGrandparent][$current] = $data;
		}else if ($current == "OPTION") {
			$xml_data[$currentGrandparent][$currentParent][$current][$optionCounter] = $data;
		}else {
			$xml_data[$currentGrandparent][$currentParent][$current] = $data;
		}
			
		//print_r($xml_data);
	}
	xml_set_character_data_handler($xmlparser, "tag_contents"); //calls the xml parser, sets the data read function
	$filename = $xmlFile; //file to read
	if (!($fp = fopen($filename, "r"))) { die("cannot open ".$filename); }

	while ($data = fread($fp, 4096)){ //read that file
   		$data=eregi_replace(">"."[[:space:]]+"."<","><",$data); //removes whitespace
   		if (!xml_parse($xmlparser, $data, feof($fp))) { //run the code 
			$reason = xml_error_string(xml_get_error_code($xmlparser)); //or tell me why not
      		$reason .= xml_get_current_line_number($xmlparser);
      		die($reason);
   		}
	}
	xml_parser_free($xmlparser);
	
	//echo "End of file reached:<br/>";
	global $xml_data;
	//print_r($xml_data);
}

//dataToStrings() writes the database based on the parsed XML as well as constructs a backend HTML String
function dataToStrings() {
	$SQLhandle;
	$optionArray = array();
	global $tableArray,$optionArray, $displayNameArray, $xml_data, $db_host, $db_username, $db_password, $db_name;
	global $optionCounter;
	global $fieldsForDeletionString, $inputElementsString, $fieldVarsString, $postDataVarsString, $editPostDataSQLString, $newNamesPostDataSQLString, $newValuesPostDataSQLString; 
	global $backListElements, $frontListElements, $frontListSQL, $backListSQL, $listPageNav, $SQLconnect, $sortable;
	
//install table sql statement
	foreach ($xml_data as $currentGrandparent => $value) {
		$SQLhandle = ($currentGrandparent != "GLOBALS") ? "CREATE TABLE $currentGrandparent (id INT NOT NULL AUTO_INCREMENT, ": "";
		echo ($currentGrandparent != "GLOBALS") ? "<h3>Parsing and Building Table [$currentGrandparent]</h3>":"";
		//echo  "<br />" . $currentGrandparent;
		$fieldNum = 1;
		$backListElements = "\n\t\t$"."bodyString .= \"\\"."n<div class='backListRecord $currentGrandparent"."_record' id='$"."id'>\";";
		foreach ($xml_data[$currentGrandparent] as $currentParent => $value) {
			if ($currentGrandparent == "GLOBALS") {
				//echo "<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" . $value;
				globalData($currentParent,$value);
			}else if ($currentGrandparent == "LINKED_TABLES") {
				echo "<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" . $currentParent;
			}else {
				if ($currentParent == "DISPLAYNAME") {
					$displayNameArray[$currentGrandparent] = $value;
				}
				//else if ($currentParent == "NUM_LINKTABLEFIELDS") { echo "\n<br/>NUM_LINKTABLEFIELDS = $value"; }
				else if ($currentParent == "SORTABLE") {
/* 					$backListElements = "test"; */
					$backListElements .= "\n\t\t$"."bodyString .= \"\\"."n  <div class='backListElement'><div class='dragIcon'></div></div>\";";
					 //$sortable = $value;
				}
				else if ($currentParent == "STATIC" || $currentParent == "HAS_TITLE") {
					//Do static/has_title stuff
				}
				else {
					if ($currentParent != "NUM_LINKTABLEFIELDS" && $currentParent != "STATIC" && $currentParent != "HAS_TITLE") {echo "{$fieldNum} {<b>$currentParent</b>}{<b>\"".$xml_data[$currentGrandparent][$currentParent]["DISPLAYNAME"]."\"</b>}  SQL DATATYPE: ". $xml_data[$currentGrandparent][$currentParent]["SQLDATATYPE"] . "<br/>" ;}
					if ($xml_data[$currentGrandparent][$currentParent]["SQLDATATYPE"] != "NONE") {
						$numOfLinkTableFields = $numOfFields = $isSortable = $isStatic = $hasLinkTable = $hasTitleField = "";
						if ($xml_data[$currentGrandparent]["NUM_LINKTABLEFIELDS"]) {
						//is there a link table field counter in the array for this table?
							$numOfLinkTableFields = $xml_data[$currentGrandparent]["NUM_LINKTABLEFIELDS"];
							$hasLinkTable = 1;
							//echo "There is a linkTable node in the array.";
							//then make the link table counter variable for this table equal to that and include one for the counter as a field itself
						}
						if ($xml_data[$currentGrandparent]["SORTABLE"]) {$isSortable = 1;}
						if ($xml_data[$currentGrandparent]["STATIC"]) {$isStatic = 1;}
						if ($xml_data[$currentGrandparent]["HAS_TITLE"]) {$hasTitleField = 1;}
						$numOfFields = sizeof($xml_data[$currentGrandparent])-(1+$hasLinkTable+$isSortable+$isStatic+$hasTitleField);
						//the number of fields is equal to the number of points in the array, minus one for the display name and the link table field counter
						$isSortable = ($isSortable)?1:0;
						$isStatic = ($isStatic)?1:0;
						$hasTitleField = ($hasTitleField)?1:0;
						//echo "<p>fieldNum : $fieldNum // numOfFields : $numOfFields</p>";
						if ($currentParent != "NUM_LINKTABLEFIELDS") {
							$fieldVarsString .= "\t\t$$currentParent = $%rowArray[\"" . $currentParent . "\"];\n";
							$postDataVarsString .= "\t\t$$currentParent = htmlentities($%_POST[\"" . $currentParent . "\"],ENT_QUOTES);\n";
						}
						$currDataType = $xml_data[$currentGrandparent][$currentParent]["SQLDATATYPE"];
						if ($fieldNum < $numOfFields-$numOfLinkTableFields && $currentParent !== "NUM_LINKTABLEFIELDS") { 
							$editPostDataSQLString .= ($currDataType != "TIMESTAMP") ? " $currentParent = '$$currentParent', " : " $currentParent = FROM_UNIXTIME($$currentParent), ";
							$newNamesPostDataSQLString .= "$currentParent,";
							$newValuesPostDataSQLString .= ($currDataType != "TIMESTAMP") ? "'$$currentParent'," : "CURDATE(), ";
						} else if ($currentParent != "NUM_LINKTABLEFIELDS"){
							$editPostDataSQLString .= ($currDataType != "TIMESTAMP") ? " $currentParent = '$$currentParent' " : " $currentParent = FROM_UNIXTIME($$currentParent) ";
							$newNamesPostDataSQLString .= "$currentParent";
							$newValuesPostDataSQLString .= ($currDataType != "TIMESTAMP") ? "'$$currentParent'" : "CURDATE()";
							echo "<p>[Total Nodes: ".sizeof($xml_data[$currentGrandparent])." ],[Link Table Fields: $numOfLinkTableFields ], [isSortable: $isSortable],[isStatic: $isStatic], [hasTitleField: $hasTitleField], [ Total Fields: $numOfFields]</p>";
						}
						$fieldNum++;
					}
				//echo "<p>$editPostDataSQLString</p>";
				

				$SQLhandle .= "";
				} //end 2nd else
				if ($currentParent != "DISPLAYNAME" && $currentParent != "SORTABLE" && $currentParent != "STATIC" && $currentParent != "HAS_TITLE") {
					foreach ($xml_data[$currentGrandparent][$currentParent] as $current => $value) {
						//$optionName = $current . $optionCounter;
						switch ($current) {
							case "SQLDATATYPE":
								if ($value != "NONE")
									$SQLhandle .= "$currentParent " . SQLdatatype($value) . ", ";
								break;
							case "ENTRYMETHOD":
								$inputElementsString .= entryMethod($value,$currentParent, $currentGrandparent, $optionArray);
								if ($value == 'fileUpload') {$fieldsForDeletionString .= "$.fileDelete(ID,'$currentParent');\n";}
								if ($value == 'fileUploadCrop') {$fieldsForDeletionString .= "$.fileDelete(ID,'$currentParent');\n";}
								if ($value == 'fileUploadThumb') {$fieldsForDeletionString .= "$.fileDelete(ID,'$currentParent');\n";}
								break;
							case "FRONTLIST":
							case "BACKLIST":
								buildVisibleElement($value,$current,$currentParent,$currentGrandparent);
								break;
							case "OPTION":
								$optionArray = $value;
	/*
								$optionArray[]=$value;
								print_r($optionArray);
								$optionCounter++;
	*/
								break;
							case "DISPLAYNAME":
								$displayNameArray[$currentParent] = $value;
								//print_r($displayNameArray);
								break;
							case "CHILD":
							case "CHILD_TABLENAME":
							case "CHILD_FIELDNAME":
							case "LINK_TABLENAME":
							case "WIDTH":
							case "HEIGHT":
								break;
							default:
								echo "ERROR: Field attribute not recognized...</br>";
								break;
						} //end switch
						
					} // end foreach CURRENT
				}
			} //end if
		} //end foreach CURRENTPARENT		
		$SQLhandle .= ($currentGrandparent != "GLOBALS") ? " PRIMARY KEY (id) );": "";
		if ($SQLhandle) {echo "<br />" . $SQLhandle . "<br/>";}
		//#### execute SQL calls and createWrite for TABLES only
		if (($currentGrandparent != "GLOBALS") && ($currentGrandparent != "LINKED_TABLES")) {
			$SQLconnect = mysql_connect($db_host,$db_username,$db_password);
			$fieldVarsString .= "\t\t$%id = $%rowArray[\"id\"];\n";
			createWrite($currentGrandparent);
			createList($currentGrandparent);
			//#### createGroupWrite($currentGrandparent);
			//#### createGroupList($currentGrandparent);
			createLinkedTableList($currentGrandparent);
			if ($xml_data[$currentGrandparent]["NUM_LINKTABLEFIELDS"] > 0) {
				//echo print_r($xml_data[$currentGrandparent],true);
				//createPopupSelector($currentGrandparent, $fieldVarsString);
			}
			createFrontEndSkeleton($currentGrandparent);
			$inputElementsString = $fieldsForDeletionString = $fieldVarsString = $postDataVarsString = $editPostDataSQLString = $newNamesPostDataSQLString = $newValuesPostDataSQLString = "";
			$backListElements = $frontListElements = $frontListSQL = $backListSQL = "";
			if (!$SQLconnect) { echo("SQL Connection Error: " . mysql_error() . "\n");	}
			else {
				$SQLexecute = mysql_db_query($db_name,$SQLhandle,$SQLconnect);
				if (!$SQLexecute) { echo("SQL Execution Error: " . mysql_error() . "\n$SQL\n");	}
				else {
				//echo "MySQL Table Created";
				}
			}
			//mysql_close($SQLconnect);
		} //end SQL build calls
		echo ($currentGrandparent != "GLOBALS") ? "<p>#### Finished Info on Table '$currentGrandparent'.####</p>":"";
	} //end foreach CURRENTGRANDPARENT
	//echo "meta write string:<br />" . $inputElementsString;
	//echo "field list string:<br />" . $fieldVarsString;
echo "<H2>FINISHED PRINTING</H2>";
createNav();
createHelp();
//echo "<b>listPageTabs: " . $listPageNav . "</b><br><br>";
}

function SQLdatatype($SQLdatatype) {
	$returnString;
	switch ($SQLdatatype) {
		case "VARCHAR":
			$returnString = "varchar(255)";
			break;
		case "TEXT":
			$returnString = "TEXT";
			break;
		case "DATE":
			$returnString = "DATE";
			break;
		case "INT":
			$returnString = "INT";
			break;
		case "DATETIME":
			$returnString = "DATETIME";
			break;
		case "TIME":
			$returnString = "TIME";
			break;
		case "TIMESTAMP":
			$returnString = "TIMESTAMP";
			break;
		default:
			echo " // <b>ERROR: Data Type not recognized...</b><br/>";
			break;
	}
	return $returnString;
}

function entryMethod($entrymethod, $currentParent,$currentGrandparent,$optionArray) {
	global $db_name,$db_host,$db_username,$db_password;
	global $SQLconnect;
	global $displayNameArray;
	global $xml_data;
	$returnString;
	switch ($entrymethod) {
		// !textArea 
		case "textArea":
			$returnString = "\n\t\t// Entry Method Type : {textArea}";
			$returnString .= "\n\t\techo \"<label for='$currentParent'>".$displayNameArray[$currentParent]."</label><textarea name='$currentParent' cols='40' rows='6' class='formElement $currentGrandparent"."Input'>$$currentParent</textarea>\";";
			break;
		// !textField 
		case "textField":
			$returnString = "\n\t\t// Entry Method Type : {textField}";
			$returnString .= "\n\t\techo \"<label for='$currentParent'>".$displayNameArray[$currentParent]."</label><input type='text' name='$currentParent' size='100' class='formElement $currentGrandparent"."Input' value='$$currentParent'>\";";
			break;
		// !textAreaAJAX 
		case "textAreaAJAX":
			$returnString = "echo \"<label for='$currentParent'>".$displayNameArray[$currentParent]."</label><textarea name='$currentParent' cols='40' rows='6' class='formElement $currentGrandparent"."Input'>$$currentParent</textarea>\";\n";
			break;
		// !fileUpload 
		case "fileUpload":
			$returnString = "\n\t\t// Entry Method Type : {fileUpload}";
			$returnString .= "
if ($"."id) {
	echo \"<div id='\".$"."id.\"$currentParent' class='noCrop'>
				<label for='$currentParent'>".$displayNameArray[$currentParent]."</label>\".fileUploadDisplay($$currentParent).\"\";
	echo \"<input type='file' name='$currentParent' class='fileUpload' value='$$currentParent' id='\".$"."id.\"'/><div class='originalFile'><input type='hidden' name='$currentParent' value='$$currentParent' /></div></div>\";	
}
else {
	echo \"<div id='new_item_$currentParent'  class='noCrop'><label for='$currentParent'>".$displayNameArray[$currentParent]."</label><div class='new'></div>\";
	echo \"<input type='file' name='$currentParent' class='fileUpload' value='$$currentParent' /><div class='originalFile'><input type='hidden' name='$currentParent' value='$$currentParent' /></div></div>\";	
}";
			break;
		// !fileUploadCrop 
		case "fileUploadCrop":
			$width = $xml_data[$currentGrandparent][$currentParent]["WIDTH"];
			$height = $xml_data[$currentGrandparent][$currentParent]["HEIGHT"];
			$returnString = "\n\t\t// Entry Method Type : {fileUploadCrop}";
			$returnString .= "\n\t\t$"."varName = \"$currentParent\";
		if ($"."id) {
			echo \"<div class='fileCropContainer'><div id='$"."id\".\"$currentParent' class='fileUploadCrop'><label for='$currentParent'>".$displayNameArray[$currentParent]."</label>\".fileUploadDisplay($$currentParent).\"\";
			echo \"<input type='file' name='$currentParent' class='fileUpload' value='$$currentParent' id='$"."id'/><div class='originalFile'><input type='hidden' name='$currentParent' class='formElement  $currentGrandparent"."Input' value='$$currentParent' /></div></div>
						<input type='hidden' id=\\\"$"."id\".\"$currentParent"."_width\\\" value='$width'>
						<input type='hidden' id=\\\"$"."id\".\"$currentParent"."_height\\\" value='$height'>\";}
		else {
			echo \"<div class='fileCropContainer'><div id='new_item_$currentParent' class='fileUploadCrop'><label for='$currentParent'>".$displayNameArray[$currentParent]."</label><div class='new'></div>\";
			echo \"<input type='file' name='$currentParent' class='fileUpload' value='$$currentParent' id='$"."id'/><div class='originalFile'><input class='formElement  $currentGrandparent"."Input' type='hidden' name='$currentParent' value='' /></div></div>
						<input type='hidden' id=\\\"$"."id\".\"new_item_$currentParent"."_width\\\" value='$width'>
						<input type='hidden' id=\\\"$"."id\".\"new_item_$currentParent"."_height\\\" value='$height'>\";}";
			break;
		// !fileUploadThumb 
		case "fileUploadThumb":
			$returnString = "\n\t\t// Entry Method Type : {fileUploadThumb}";
			$returnString .= "
		if ($"."id) {
			echo \"<div id='$"."id\".\"$currentParent' class='fileUploadThumb'><label for='$currentParent'>".$displayNameArray[$currentParent]."</label>\";
			if (!$$currentParent) {
				echo \"<div class='previewBox'><img src='' class='preview' /></div>\";}
			else {
				echo \"<div class='previewBox'><img src='$$currentParent' class='preview'></div>\";}
			echo \"<input type='hidden' class='formElement $currentGrandparent"."Input' name='$currentParent' value='$$currentParent' /></div></div><br clear='all' />\";	
		}
		else {
			echo \"<div id='new_item_$currentParent' class='fileUploadThumb' style='display:none;'><label for='$currentParent'>".$displayNameArray[$currentParent]."</label>\";
			if (!$$currentParent) {
				echo \"<div class='previewBox'><img src='' class='preview' /></div>\";}
			else {
				echo \"<div class='previewBox'><img src='$$currentParent' class='preview'></div>\";}
			echo \"<input type='hidden' class='formElement $currentGrandparent"."Input' name='$currentParent' value='' /></div></div><br clear='all' />\";
		}";			
			break;
		// !dropDown 
		case "dropDown":
			$returnString = "echo \"<label for='$currentParent'>".$displayNameArray[$currentParent]."</label><select name='$currentParent' class='formElement $currentGrandparent"."Input'>\n";
			for ($i = 1; $i <= sizeof($optionArray);$i++) {	
				$returnString .= "<option \";";
				$returnString .= " if ($$currentParent == \"" . $optionArray[$i] . "\") {echo \" selected='selected' \";}";
				$returnString .= "echo \"value='". $optionArray[$i] . "'>". $optionArray[$i] . "</option>\n";
				//print_r($optionArray);
			}
			$returnString .= "</select>\n\";\n";
			break;
		// !dropDown_related 
		case "dropDown_related":
			$child_tablename = $xml_data[$currentGrandparent][$currentParent]["CHILD_TABLENAME"];
			$child_fieldname = $xml_data[$currentGrandparent][$currentParent]["CHILD_FIELDNAME"];
			$returnString = "echo \"<div class='relationship'><label for='$currentParent'>".$displayNameArray[$currentParent]."</label><select name='$currentParent' class='dropDown_related formElement $currentGrandparent"."Input'><option value='$$currentParent'></option></select>
			<a class='dropDown_related_addBtn positiveBtns'>ADD OPTION</a>
			</div>
			<script type='text/javascript'>
			var $currentParent"."_child_tablename = '$child_tablename';
			var $currentParent"."_child_fieldname = '$child_fieldname';

			</script>\";\n";
			break;
		// !date 
		case "date":
			$returnString = "\n\t // Entry Method Type : {date}";
			$returnString .= "
		if ($"."id) {
				echo \"<div class='date' id='$currentParent'><label for='$currentParent'>".$displayNameArray[$currentParent]."</label><input class='hasdatepicker formElement $currentGrandparent"."Input' type='text' id='$currentParent"."_datepicker' value=\\\"\"  . strftime('%m',strtotime($$currentParent)) . \"/\" . strftime('%d',strtotime($$currentParent)) .\"/\". strftime('%Y',strtotime($$currentParent)) . \"\\\" /><input type='hidden' name='$currentParent' id='$currentParent"."_datestore' value='$"."$currentParent'></div>\";
		}
		else {
			echo \"<div class='date' id='$currentParent'><label for='$currentParent'>".$displayNameArray[$currentParent]."</label><input class='hasdatepicker formElement $currentGrandparent"."Input' type='text' id='$currentParent"."_datepicker' /><input type='hidden' name='$currentParent' id='$currentParent"."_datestore'></div>\";
		}";
			break;
		// !dateTime 
		case "dateTime":
			//if we are editing a page print out the data already inside the row -> else print empty input fields
			$returnString = "
			if ($"."id) {
				echo \"<div class='dateTime' id='$currentParent'><label for='$currentParent'>".$displayNameArray[$currentParent]."</label><input class='hasdatepicker formElement $currentGrandparent"."Input' type='text' id='$currentParent"."_datepicker' value=\\\"\"  . strftime('%m',strtotime($$currentParent)) . \"/\" . strftime('%d',strtotime($$currentParent)) .\"/\". strftime('%Y',strtotime($$currentParent)) . \"\\\" /><input type='hidden' id='$currentParent"."_datestore'> @ <input type='text' class='hastimepicker formElement $currentGrandparent"."Input' id='$currentParent"."_timepicker' value='\".strftime('%I',strtotime($$currentParent)).\":\".strftime('%M',strtotime($$currentParent)).\" \". strftime('%P',strtotime($$currentParent)) .\"' /><input type='hidden' id='$currentParent"."_timestore' value='\".strftime('%I',strtotime($$currentParent)).\":\".strftime('%M',strtotime($$currentParent)).\":\". strftime('%S',strtotime($$currentParent)) .\"' /></div>\";
			}
			else {
				echo \"<div class='date' id='$currentParent'><label for='$currentParent'>".$displayNameArray[$currentParent]."</label><input type='text' class='formElement $currentGrandparent"."Input month' name='".$currentParent."_month' size='2'/>&nbsp;<input type='text' class='formElement $currentGrandparent"."Input day' name='".$currentParent."_day' size='2'/>&nbsp;<input type='text' class='formElement $currentGrandparent"."Input year' name='".$currentParent."_year' size='4'/>&nbsp;&nbsp;<input type='text' class='formElement $currentGrandparent"."Input hour' name='".$currentParent."_hour' size='4'/>:<input type='text' class='formElement $currentGrandparent"."Input minute' name='".$currentParent."_minutes' size='4'/>:<input type='text' class='formElement $currentGrandparent"."Input second' name='".$currentParent."_seconds' size='4'/></div>\";
			}";
			break;
		// !time 
		case "time":
			//if we are editing a page print out the data already inside the row -> else print empty input fields
			$returnString = "
			if ($"."id) {
				echo \"<div class='dateTime' id='$currentParent'><label for='$currentParent'>".$displayNameArray[$currentParent]."</label><input type='text' class='hastimepicker formElement $currentGrandparent"."Input' id='$currentParent"."_timepicker' value='\".strftime('%I',strtotime($$currentParent)).\":\".strftime('%M',strtotime($$currentParent)).\" \". strftime('%P',strtotime($$currentParent)) .\"' /><input type='hidden' name='$currentParent' id='$currentParent"."_timestore' value='\".strftime('%I',strtotime($$currentParent)).\":\".strftime('%M',strtotime($$currentParent)).\":\". strftime('%S',strtotime($$currentParent)) .\"' /></div>\";
			}
			else {
				echo \"<div class='date' id='$currentParent'><label for='$currentParent'>".$displayNameArray[$currentParent]."</label><input type='text' class='hastimepicker formElement $currentGrandparent"."Input' id='$currentParent"."_timepicker' value='12:00 am' /><input type='hidden' name='$currentParent' id='$currentParent"."_timestore' value='00:00:00' /></div>\";
			}";
			break;
		// !timeStamp 
		case "timeStamp":
			//if we are editing a page print out the data already inside the row -> else print current time
			$thisFieldName = $currentParent;
			$thisTableName = $currentGrandparent;
			$returnString = "
			if ($"."id)
				echo \"\n\t\t<input type='hidden' class='formElement $thisTableName"."Input' name='$thisFieldName' id='$thisFieldName"."_timeStamp'  value='\".strtotime($$currentParent).\"' />\n\";";
				//echo \"\n\t\t<input type='hidden' class='formElement $thisTableName"."Input' name='$thisFieldName' id='$thisFieldName"."_timeStamp'  value='\". strftime('%m',strtotime($$currentParent)) . \"-\" . strftime('%d',strtotime($$currentParent)) .\"-\". strftime('%Y',strtotime($$currentParent)) .\" \".strftime('%I',strtotime($$currentParent)).\":\".strftime('%M',strtotime($$currentParent)).\":\". strftime('%S',strtotime($$currentParent)) .\"' />\n\";";
			break;
		case "groupItemEdit":
			$childTableBase = $xml_data[$currentGrandparent][$currentParent]["CHILD_TABLENAME"];
			$childTableInclude =  $childTableBase . "_groupwrite.php";
			$returnString .= "$$currentGrandparent"."_id = $"."id;";
			$returnString .= "$"."parentTable_SQL_where = \"$currentGrandparent"."_id = $"."id\";";
			$returnString .= "$"."parentTable = \"$currentGrandparent\";";
			$returnString .= "echo \"<script type='text/javascript'> child_tableName = '$childTableBase';</script>\";";
			//#######parentTable variable is not unique, we need to clear out this inconsistency in the FUTURE for multiple groupItemEdit's on one page!!!!!
			$returnString .= "require_once('$childTableInclude');";
			break;
		case "groupItemList":
			$childTableBase = $xml_data[$currentGrandparent][$currentParent]["CHILD_TABLENAME"];
			$childTableInclude =  $childTableBase . "_grouplist.php";
			$returnString .= "$$currentGrandparent"."_id = $"."id;";
			$returnString .= "$"."parentTable_id = \"$currentGrandparent"."_id\";";
			$returnString .= "$"."parentTable_SQL_where = \"$currentGrandparent"."_id = $"."id\";";
			$returnString .= "$"."parentTable = \"$currentGrandparent\";";
			$returnString .= "if ($"."id) {";
			$returnString .= "echo \"<label>".$displayNameArray[$currentParent]."</label>\";";						
			$returnString .= "echo \"<div class='groupItemList'>\";";			
			$returnString .= "require_once('$childTableInclude');";
			$returnString .= "echo \"</div>\";}";			
			break;
		// !linkedTableList 
		case "linkedTableList":
			$child_tablename = $xml_data[$currentGrandparent][$currentParent]["CHILD_TABLENAME"];
			$child_fieldname = $xml_data[$currentGrandparent][$currentParent]["CHILD_FIELDNAME"];
			$isSortable = $xml_data[$child_tablename]["SORTABLE"];
			$sortableClass = $sortableSQL = "";
			if ($isSortable) { $sortableClass = "sortable"; $sortableSQL = " sort_order INT,";}
			$link_tablename = $xml_data[$currentGrandparent][$currentParent]["LINK_TABLENAME"];
			$link_sql = "CREATE TABLE $link_tablename (id INT NOT NULL AUTO_INCREMENT, $sortableSQL parent_id INT, child_id INT, PRIMARY KEY (id) );";
			echo "<p>LINK SQL = $link_sql</p>";
			$SQLlinkconnect = mysql_connect($db_host,$db_username,$db_password);
			if (!$SQLlinkconnect) { echo("<b>SQL Link Connection Error:</b> " . mysql_error() . "\n");	}
			else {
				$SQLlinkExecute = mysql_db_query($db_name,$link_sql,$SQLlinkconnect);
				if (!$SQLlinkExecute) { echo("<em>SQL Link Execution Error:</em> " . mysql_error() . "\n");	}
				else {
					echo "<em>".$link_sql . "</em>";
				}
			}
			echo "<em>".$link_sql . "</em>";
			
			// Create _selector.php page
			$tableName = $child_tablename;
			global $fieldVarsString;
			//createPopupSelector($tableName,$link_tablename, $fieldVarsString);
			 
			$childTableInclude = $child_tablename . "_linkedtablelist.php";
			$returnString = "\n\t // Entry Method Type : {linkedTableList}";
			$returnString .= "
    $$currentGrandparent"."_id = $"."id;
    $"."linkTableName = \"$link_tablename\";
    $"."childTableName = \"$child_tablename\";
    $"."parentTable_id = \"$currentGrandparent"."_id\";
    $"."parentTable_SQL_where = \"$currentGrandparent"."_id = $"."id\";
    $"."parentTable = \"$currentGrandparent\";
    if ($"."id) { ?>\n
    <label>".$displayNameArray[$currentParent]."</label> 
    <script type='text/javascript'>
      var child_tablename = '$child_tablename',
          child_fieldname = '$child_fieldname',
          link_tablename = '$link_tablename';
      $(function() {
        $('#$link_tablename .sortable').sortable({ 
          items: '.backListRecord',
          handle: '.dragIcon',
          update: function() {
            var orderString = '';
            var order = $('#$link_tablename .sortable').sortable('toArray');
            for (i=0;i<order.length;i++) {
              if (i != 0) { 
                orderString = orderString + '&'; 
              }
              orderString = orderString + 'order[]='+order[i];
            }
            console.log(order);
            $.ajax({
              type: 'GET',
              url: 'ajax.php',
              data: 'AJAXtask=linksortorderUpdate&link_tablename=$link_tablename&parent_recordID='+parent_id+'&tablename=$child_tablename&'+orderString,
              success: function(msg){
                //alert( \'Data Saved: \' + msg );
              }
            });  
          }
        }); // end .sortable()
      }); // end jQuery
    </script>		
<?php
    echo \"
    <div class='linkedTable' id='$link_tablename'>
      <div class='linkedTableList $sortableClass'>\";			
      require_once('$childTableInclude');
    echo \"
      </div>\";
    echo \"
<div class='popupLink poplight' id='poplight_1'>Choose from existing items</div>
<!--POPUP START-->
<div id='popup1' class='popup_block'>
  <div class='ajaxDestination'></div>	   
</div>
<!-- POPUP END -->
\";
    echo \"<a class='newBtn positiveBtns' href='" . $child_tablename . "_write.php?foreignKey=\".$".$currentGrandparent."_id.\"&sessionDepth=\".($"."_GET['sessionDepth']+1).\"&linkedChild=$child_tablename'>NEW RECORD</a>\";";

			$returnString .= "						
			";			
			$returnString .= "echo \"</div>\";}";			
			break;
		case "hidden":
			$returnString .= "echo \"<input class='formElement' type='hidden' name='$currentParent' value='$$currentParent' />\";";
			break;
		case "foreignKey":
			$returnString .= "if (!$"."foreignKey) { $"."foreignKey = $$currentParent; }";
			$returnString .= "echo \"<input class='formElement' type='hidden' name='$currentParent' value='$"."foreignKey' />\";";
			break;
		default:
			echo " // <b>ERROR: Entry Type not recognized...</b><br/>";
			break;	}
	return $returnString;
}

function globalData($paramName, $value) {
	global $db_host;
	global $db_username;
	global $db_password;
	global $db_name;
	global $images_path;
	global $movies_path;
	global $thumbs_path;
	global $pdf_path;
	global $audio_path;
	global $http_root;
	global $server_root;
	global $site_name;

	switch ($paramName) {
		case "USERNAME":
			$db_username = $value;
			break;
		case "PASSWORD":
			$db_password = $value;
			break;
		case "DATABASE":
			$db_name = $value;
			break;
		case "HOST":
			$db_host = $value;
			break;
		case "AUDIO_PATH":
			$audio_path = $value;
			break;
		case "IMAGES_PATH":
			$images_path = $value;
			break;
		case "THUMBS_PATH":
			$thumbs_path = $value;
			break;
		case "MOVIES_PATH":
			$movies_path = $value;
			break;
		case "PDF_PATH":
			$pdf_path = $value;
			break;
		case "HTTP_ROOT":
			$http_root = $value;
			break;
		case "SERVER_ROOT":
			$server_root = $value;
			break;
		case "SITENAME":
			$site_name = $value;
			break;
		default:
			echo " // <b>ERROR: Global Parameter not recognized...</b><br/>";
			break;
	}
}

function buildVisibleElement($displayType, $page, $fieldName, $tableName) {
	global $db_host;
	global $db_username;
	global $db_password;
	global $db_name;

	global $frontListElements, $frontListSQL, $backListElements, $backListSQL, $displayNameArray,$xml_data;
	//echo "<b>displayType: $displayType // page : $page // fieldName : $fieldName</b>";
	if ($page == "FRONTLIST") {
		switch ($displayType) {
			case "text":
				$frontListElements .= "\n\t\t$"."bodyString .= \"\\"."n<div class='frontListElement'>".$displayNameArray[$fieldName].": $$fieldName</div>\";";
				break;
			case "image":
				$frontListElements .= "\n\t\t if ($".$fieldName.") { \$"."bodyString .= \"\\"."n<img src='$"."$fieldName' class='frontListElement'>\";}";
				break;
			case "date":
			case "timeStamp":
				$frontListElements .= "\n\t\t$"."bodyString .= \"\\"."n<div class='frontListElement'>".$displayNameArray[$fieldName].": \".strftime('%m',strtotime($$fieldName)).\" \".strftime('%d',strtotime($$fieldName)).\" \".strftime('%Y',strtotime($$fieldName)).\"</div>\";";
				break;
			case "dateTime":
				$frontListElements .= "\n\t\t$"."bodyString .= \"\\"."n<div class='frontListElement'>".$displayNameArray[$fieldName].": \".strftime('%m',strtotime($$fieldName)).\" \".strftime('%d',strtotime($$fieldName)).\" \".strftime('%Y',strtotime($$fieldName)).\" \".strftime('%I',strtotime($$fieldName)).\":\".strftime('%M',strtotime($$fieldName)). \":\".strftime('%S',strtotime($$fieldName)). \"</div>\";";
				break;
			case "time":
				$frontListElements .= "\n\t\t$"."bodyString .= \"\\"."n<div class='frontListElement'>".$displayNameArray[$fieldName].": \".strftime('%I',strtotime($$fieldName)).\":\".strftime('%M',strtotime($$fieldName)). \":\".strftime('%S',strtotime($$fieldName)). \"</div>\";";
				break;
			case "relatedData":
				$child_tablename = $xml_data[$tableName][$fieldName]["CHILD_TABLENAME"];
				$child_fieldname = $xml_data[$tableName][$fieldName]["CHILD_FIELDNAME"];
				$frontListElements .= "\n\t$"."SQLrelatedData = \"SELECT $child_fieldname AS fieldname, id FROM $child_tablename WHERE id = '$$fieldName' \";\n";
				$frontListElements .= "\t$"."SQLrelatedResult = $"."db->query($"."SQLrelatedData);\n";
				$frontListElements .= "\twhile($"."relatedRowArray = $"."db->fetch_array($"."SQLrelatedResult) ) {\n";
				$frontListElements .= "\t\t$"."fieldName = $"."relatedRowArray[\"fieldname\"];\n";
				$frontListElements .= "\t\t$"."relatedId = $"."relatedRowArray[\"id\"];\n";
				$frontListElements .= "\t\t$"."bodyString .= \"\\"."n<div class='frontListElement'>".$displayNameArray[$fieldName].": $"."fieldName</div>\";\n";
				$frontListElements .= "\t}";
				break;
			case "none":
				break;
			default:
				echo " // <b>ERROR: Front List Display Type in fieldname '$fieldName' not recognized. Type ['$displayType']...</b><br/>";
				break;
		}
		if ($displayType != "none") {
			$frontListSQL = "$fieldName, ";
		}
	}
	if ($page == "BACKLIST") {
		switch ($displayType) {
			case "text":
				if (strtoupper($displayNameArray[$fieldName]) == "TITLE")
					$backListElements .= "\n\t\t$"."bodyString .= \"\\"."n  <div class='backListElement backListTitle'>$$fieldName</div>\";";
				else
				$backListElements .= "\n\t\t$"."bodyString .= \"\\"."n  <div class='backListElement'>".$displayNameArray[$fieldName].": $$fieldName</div>\";";
				break;
			case "image":
				$backListElements .= "\n\t\t$"."imgFileTypes = array('JPG','PEG','GIF','PNG');";
				if( substr($fieldName,-6) == "_thumb" ) { // if this is a thumbnail field, do the thumb checkeroo
					$backListElements .= "\n\t\t$"."fileEXT = strtoupper( substr($".substr($fieldName,0, strlen($fieldName)-6).", -3) );";
					$backListElements .= "\n\t\tif ( !in_array($"."fileEXT, $"."imgFileTypes) ) {";
					$backListElements .= "\n\t\t\t$"."bodyString .= \"\\"."n  <img src='images/defaultThumbnail.png' class='backListElement'>\";";
					$backListElements .= "\n\t\t} else if ($".$fieldName.") {";
					$backListElements .= "\n\t\t\t$"."bodyString .= \"\\"."n  <img src='$".$fieldName."' class='backListElement'>\";";
					$backListElements .= "\n\t\t}";
				} else {
					$backListElements .= "\n\t\t if ($".$fieldName.") { "."$"."bodyString .= \"\\"."n<img src='$"."$fieldName' class='backListElement'>\";}";
				}
				break;
			case "date":
			case "timeStamp":
				$backListElements .= "\n\t\t$"."bodyString .= \"\\"."n  <div class='backListElement'>".$displayNameArray[$fieldName]." : \".strftime('%m',strtotime($$fieldName)).\"-\".strftime('%d',strtotime($$fieldName)).\"-\".strftime('%Y',strtotime($$fieldName)).\"</div>\";";
				break;
			case "dateTime":
				$backListElements .= "\n\t\t$"."bodyString .= \"\\"."n  <div class='backListElement'>\".strftime('%m',strtotime($$fieldName)).\" \".strftime('%d',strtotime($$fieldName)).\" \".strftime('%Y',strtotime($$fieldName)).\" \".strftime('%i',strtotime($$fieldName)).\":\".strftime('%s',strtotime($$fieldName)).\"</div>\";";
				break;
			case "relatedData":
				$child_tablename = $xml_data[$tableName][$fieldName]["CHILD_TABLENAME"];
				$child_fieldname = $xml_data[$tableName][$fieldName]["CHILD_FIELDNAME"];
				$backListElements .= "\n\t\t$"."SQLrelatedData = \"SELECT $child_fieldname AS fieldname, id FROM $child_tablename WHERE id = '$$fieldName' \";\n";
				$backListElements .= "\t\t$"."SQLrelatedResult = $"."db->query($"."SQLrelatedData);\n";
				$backListElements .= "\t\twhile($"."relatedRowArray = $"."db->fetch_array($"."SQLrelatedResult) ) {\n";
				$backListElements .= "\t\t\t$"."fieldName = $"."relatedRowArray[\"fieldname\"];\n";
				$backListElements .= "\t\t\t$"."relatedId = $"."relatedRowArray[\"id\"];\n";
				$backListElements .= "\t\t\t$"."bodyString .= \"\\"."n<div class='frontListElement'>".$displayNameArray[$fieldName].": $"."fieldName</div>\";\n";
				$backListElements .= "\t\t}";
				break;
			case "none":
				break;
			default:
				echo " // <b>ERROR: Back List Display Type in fieldname '$fieldName' not recognized. Type ['$displayType']...</b><br/>";
				break;
		}
		if ($displayType != "none") {
			$backListSQL = "$fieldName, ";
		}
	}
}

function writePHP($output, $fileName) {
	$myfile = getcwd() . "/admin/". $fileName;
	//echo "myfile = " . $myfile;
	echo "<a href='admin/". $fileName . "'>$fileName</a><br/>";
	$fh = fopen($myfile, 'w') or die("can't open file");
	fwrite($fh, $output);
	fclose($fh);
}

/* navlist checker (within the creatNav function here, replace or merge as needed) */
function createNav() {
	global $tableArray,$displayNameArray;
	for ($i=0; $i < sizeof($tableArray);$i++) {
			$navSource .= "\t\t<div class='otherTable <?php if ($"."currentNavTable == \"".$tableArray[$i]."\") { echo \"currentTable\";} ?>'><a href='".$tableArray[$i]."_list.php'>".$displayNameArray[$tableArray[$i]]."</a></div>\n";
	}
	// add "help" section to the navigation
	$navSource .= "\t\t<div class='navlistHR'>&nbsp;</div>";
	$navSource .= "\n\t\t<div class='otherTable <?php if ($"."currentNavTable == \"help\") {echo \"currentTable\";} ?>'><a href='help.php'>Help</a></div>\n";
	$fileName = "navlist.php";
	$navFilePath = getcwd() . "/admin/". $fileName;
	if (!file_exists($navFilePath)) {
		writePHP($navSource,$fileName);
	}
}
function createWrite($tableName) {
	global $tableArray,$displayNameArray,$siteName,$inputElementsString, $fieldVarsString, $postDataVarsString, $db_password, $db_username, $db_host, $db_name;
	include('meta-templates/writePage.php');
	$fileName = $tableName . "_write.php";
	writePHP($pageSource,$fileName);
} //end function creatWrite()

function createList($tableName) {
	global $xml_data,$siteName,$tableArray,$displayNameArray,$postDataVarsString, $editPostDataSQLString, $fieldsForDeletionString, $inputElementsString, $fieldVarsString, $db_password, $db_username, $db_host, $db_name, $backListElements, $backListSQL,$newNamesPostDataSQLString, $newValuesPostDataSQLString, $listPageNav;
	$isSortable = $xml_data[$tableName]["SORTABLE"];
	$isStatic = $xml_data[$tableName]["STATIC"];
	$hasTitleField = $xml_data[$tableName]["HAS_TITLE"];
	include('meta-templates/listPage.php');
	$fileName = $tableName . "_list.php";
	writePHP($pageSource,$fileName);
}

function createGroupWrite($tableName) {
	global $fieldsForDeletionString,$tableArray,$displayNameArray,$siteName,$inputElementsString, $fieldVarsString, $postDataVarsString, $db_password, $db_username, $db_host, $db_name;
	include('meta-templates/groupWrite.php');
	$fileName = $tableName . "_groupwrite.php";
	writePHP($pageSource,$fileName);
} //end function creatGroupWrite()

function createGroupList ($tableName) {
	global $siteName,$tableArray,$displayNameArray,$postDataVarsString, $editPostDataSQLString, $fieldsForDeletionString, $inputElementsString, $fieldVarsString, $db_password, $db_username, $db_host, $db_name, $backListElements, $backListSQL,$newNamesPostDataSQLString, $newValuesPostDataSQLString, $listPageNav;
	include('meta-templates/groupList.php');
	$fileName = $tableName . "_grouplist.php";
	writePHP($pageSource,$fileName);
} //end function creatGroupList()

function createGlobalData () {
	global $db_host;
	global $db_username;
	global $db_password;
	global $db_name;
	global $images_path,$audio_path,$movies_path,$thumbs_path,$pdf_path;
	global $http_root,$server_root;
	global $site_name;
	
	if ($audio_path) {
	mkdir($server_root . $audio_path);
	}
	if ($images_path) {
	mkdir($server_root . $images_path);
	}
	if ($movies_path) {
	mkdir($server_root . $movies_path);
	}
	if ($thumbs_path) {
	mkdir($server_root . $thumbs_path);
	}
	if ($pdf_path) {
	mkdir($server_root . $pdf_path);
	}
	
	$pageSource = "<"."?";
	$pageSource .= "\n$"."images_path = \"$images_path\";";
	$pageSource .= "\n$"."audio_path = \"$audio_path\";";
	$pageSource .= "\n$"."movies_path = \"$movies_path\";";
	$pageSource .= "\n$"."thumbs_path = \"$thumbs_path\";";
	$pageSource .= "\n$"."pdf_path = \"$pdf_path\";";
	$pageSource .= "\n";
	$pageSource .= "\n$"."db_host = \"$db_host\";";
	$pageSource .= "\n$"."db_username = \"$db_username\";";
	$pageSource .= "\n$"."db_password = \"$db_password\";";
	$pageSource .= "\n$"."db_name = \"$db_name\";";
	$pageSource .= "\n";
	$pageSource .= "\n$"."http_root = \"$http_root\";";
	$pageSource .= "\n$"."server_root = \"$server_root\";";
	$pageSource .= "\n";
	$pageSource .= "\n$"."site_name= \"$site_name\";";

	$pageSource .= "\n?>";
	$fileName = "global_vars.php";
	writePHP($pageSource,$fileName);
}


function createLinkedTableList ($tableName) {
	global $siteName,$tableArray,$displayNameArray,$postDataVarsString, $editPostDataSQLString, $fieldsForDeletionString, $inputElementsString, $fieldVarsString, $db_password, $db_username, $db_host, $db_name, $backListElements, $backListSQL,$newNamesPostDataSQLString, $newValuesPostDataSQLString, $listPageNav,$xml_data;
	
	$isSortable = $xml_data[$tableName]["SORTABLE"];

	include('meta-templates/linkedTableList.php');
	$fileName = $tableName . "_linkedtablelist.php";
	writePHP($pageSource,$fileName);
	
	//Create the body and call createPopupSelector()
	$popupRowTemplate = $fieldVarsString.$backListElements;
	createPopupSelector($tableName, $popupRowTemplate);
} //end function creatGroupList()

function createFrontEndSkeleton($tableName) {
	global $postDataVarsString, $editPostDataSQLString, $fieldsForDeletionString, $inputElementsString, $fieldVarsString, $db_password, $db_username, $db_host, $db_name, $frontListElements, $backListSQL,$newNamesPostDataSQLString, $newValuesPostDataSQLString, $listPageNav;
		include('meta-templates/frontEndSkeleton.php');
		$fileName = $tableName . ".php";
		writePHP($pageSource,$fileName);
} // end fn createFrontEndSkeleton($tableName)

function createIndex($homePage) {
	$pageSource = "".
"<?php
require_once('$homePage');
?>";
	writePHP($pageSource,"index.php");
} // end fn createIndex()

function createPopupSelector($tableName,$rowTemplate) {
	$fileName = $tableName."_selector.php";
	$dragHandleString = "<div class='backListElement'><div class='dragIcon'></div></div>";
	$searchArray = array("%", $dragHandleString, "bodyString", "backListRecord");
	$replaceArray = array("", "", "selectorString", "selectorRecord");
	$rowTemplate = str_replace($searchArray, $replaceArray, $rowTemplate);
	include('meta-templates/popupSelector.php');
	writePHP($pageSource,$fileName);
} // end fn createIndex()

function createHelp() {
	$fileName = "help.php";
	include('meta-templates/helpPage.php');
	$helpFilePath = getcwd() . "/admin/". $fileName;
/* 	if (!file_exists($helpFilePath)) { */
		writePHP($helpSource,$fileName);
/* 	} */
} //end fn createHelp()

?>